﻿using System.Text;
using K9Nano.Updater.Extensions;
using Microsoft.Extensions.Logging;

namespace K9Nano.Updater.Client.Logging;

public class DelegateLogger : ILogger
{
    private readonly string _categoryName;
    private readonly Action<string, LogLevel, string> _logAction;

    public DelegateLogger(string categoryName, Action<string, LogLevel, string> logAction)
    {
        _categoryName = categoryName;
        _logAction = logAction;
    }

    public IDisposable? BeginScope<TState>(TState state) where TState : notnull
    {
        return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
    {
        var message = formatter(state, exception);
        if (exception == null)
        {
            _logAction(_categoryName, logLevel, message);
            return;
        }
        var sb = new StringBuilder();
        sb.AppendLine(message);
        sb.AppendLine(exception.ToFriendlyMessage());
        _logAction(_categoryName, logLevel, sb.ToString());
    }
}